package com.sztle.admodule.control.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;

import com.sztle.admodule.someutils.Utils;

public class BatteryStatusReceiver extends BroadcastReceiver {
    public int mCurrentLevel;
    public boolean mIsCharging;
    public boolean mIsUsbPlugin = false;
    public int currentLevel = 0;
    public static boolean isReceiverRegistered = false;

    @Override // android.content.BroadcastReceiver
    public void onReceive(Context context, Intent intent) {
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        int intExtra = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
        currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        isReceiverRegistered = true;
        if (plugged == BatteryManager.BATTERY_PLUGGED_USB) {
            mIsUsbPlugin = true;
        } else {
            mIsUsbPlugin = false;
        }
        if (plugged == BatteryManager.BATTERY_PLUGGED_AC ||
                plugged == BatteryManager.BATTERY_PLUGGED_USB ||
                plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
            // 设备正在充电
            mIsCharging = true;
        } else {
            // 设备未充电
            mIsCharging = false;
        }
        if (intExtra != 1 && intExtra != 2) {
            if (intExtra == 3 || intExtra == 4) {
                this.mIsCharging = false;
            }
        }

    }

    public boolean isCharging() {
        if(!isReceiverRegistered){
            BatteryManager batteryManager = (BatteryManager) Utils.getApp().getSystemService(Context.BATTERY_SERVICE);
            if (batteryManager != null) {
                int status = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_STATUS);
                int plugged = batteryManager.getIntProperty(BatteryManager.BATTERY_PLUGGED_USB);
                return status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL || plugged == BatteryManager.BATTERY_PLUGGED_USB;
            }
            return false;
        }
        return this.mIsCharging;
    }

    public boolean isUsbPlugin() {
        return mIsUsbPlugin;
    }

    public boolean isElectricityStatus() {
        return mCurrentLevel < 0 || mCurrentLevel > 100;
    }

    public int getCurrentLevel() {
        return this.mCurrentLevel;
    }

}
